var tabbarData = getTabbarList(),
	tabIndex = getHomeIndex() || 0,
	swiperFragment = null,
	tabBar = null,
	tagIndex = 0,
	tagList = getTags(),
	swiperTag = null,
	doms = {
		tagGoodsContainer: null
	};

// 初始化调用
$(() => {
	const city = JSON.parse(window.sessionStorage.getItem('city'))
	$(`#location`).html(city ? city.name : '广州市');
	doms.tagGoodsContainer = document.querySelector('#tab_content');
	initFragment();
	initTabbar();
	initBanner();
	initTagList();
	initListener();
})

/**
 * 底部按钮组对应的碎片窗口
 */
initFragment = () => {
	swiperFragment = new Swiper('.swiper_fragment', {
		initialSlide: tabIndex,
		direction: 'horizontal', //Slides的滑动方向，可设置水平(horizontal)或垂直(vertical)。
		loop: false,
		noSwiping: true, //不允许左右滑动
		autoHeight: false, //自动高度。设置为true时，wrapper和container会随着当前slide的高度而发生变化。
		onSlideChangeEnd: (swiper) => { //回调函数，swiper从一个slide过渡到另一个slide结束时执行。
			//tagIndex = swiper.activeIndex;
		}
	});
}

/**
 * 底部导航栏
 */
initTabbar = () => {
	tabBar = new TabBar({
		data: tabbarData,
		tabIndex: tabIndex,
		container: 'tabbar',
		onChange: (index) => {
			setHomeIndex(index);
			if (swiperFragment) {
				swiperFragment.slideTo(index, 500, false);
			}
		}
	})
}

/**
 * 轮播
 */
initBanner = () => {
	const bannerList = genBannerList();
	const bannerBox = $("#banner_box");
	if (!bannerList || bannerList.length === 0) return;

	const itemHtml = bannerList.map((item, index) => `
	        <div class="swiper-slide">
	            <img src="${item.img}" class="home_banner_img">
	        </div>
	    `).join('');

	bannerBox.html(itemHtml);
	const swiperBanner = new Swiper('.swiper_banner', {
		initialSlide: 0,
		pagination: '.pagination_banner',
		slidesPerView: 'auto',
		paginationClickable: true,
		spaceBetween: 30,
		noSwiping: false,
		centeredSlides: true,
		loop: true,
		autoplay: 2500,
		autoplayDisableOnInteraction: false
	});
}

/**
 * 标签
 */
initTagList = () => {
	queryTagGoods(tagIndex);
	// 调用组件（传入 Tab 容器选择器）
	const tabSlider = new TabSlider({
		container: '#tab_container',
		nav: '#tag_list',
		content: '#tab_content',
		data: tagList,
		currentIndex: tagIndex,
		onChange: index => {
			queryTagGoods(index);
		}
	});
}

/**
 * 标签内容
 */
queryTagGoods = (index) => {
	let mlist = getAllGoods(index);
	doms.tagGoodsContainer.innerHTML = '';
	setLoadingState(0);
	setTimeout(() => {
		setLoadingState(1);
		renderGoods(mlist, doms.tagGoodsContainer);
	}, 1000)
}

/**
 * 渲染标签内容
 */
const renderGoods = (goodsList, displayContainer) => {
	if (!goodsList || goodsList.length === 0) return;
	displayContainer.innerHTML = '';
	let itemHtml = '';
	goodsList.forEach(item => {
		const {
			storeId,
			primaryImage,
			title,
			spuTagList = [],
			minSalePrice,
			maxLinePrice
		} = item;
		const tagList = spuTagList.map(tag =>
			`<label class="label">${escapeHtml(tag.title)}</label>`).join('');

		itemHtml += `<div class="goods_item" onclick="onGetGoodsItem('${storeId}')"> 
							<img src="${escapeHtml(primaryImage)}" class="goods_item_img"/> 
							<div class="goods_content"> 
								<div class="title">${escapeHtml(title)}</div> 
								<div class="goods_tag">${tagList}</div> 
								<div class="goods_item_option"> 
								<div class="spec_for_price"> 
									<span class="symbol">¥</span>${getPrice(minSalePrice)} 
								</div> 
								<div class="goods-card__origin-price"> 
									<span class="symbol">¥</span>${getPrice(maxLinePrice)} 
								</div> 
								<img src="${getRootPath()}img/ic_add_card.png" class="goods_img_car" onclick="onAddCard('${storeId}')"/> 
							</div> 
						</div> 
					</div> `;
	});
	displayContainer.innerHTML = itemHtml;
};

/**
 * 点击商品
 */
onGetGoodsItem = (id) => {
	navigateTo(`page/goods/details.html?id=${id}`)
}

/**
 * 加入购物车
 */
onAddCard = (id) => {
	event.stopImmediatePropagation(); //阻止事件分发
	let subLoading = layer.open({
		type: 2,
		shadeClose: false,
		content: '正在加入购物车...'
	});
	setTimeout(() => {
		layer.close(subLoading);
		showToast('加入成功！');
	}, 1000)
}

/**
 * 将分转换为元（支持整数和字符串格式的分值）
 * @param {number|string} price - 以分为单位的价格
 * @returns {string} 以元为单位的价格字符串，保留两位小数
 */
const getPrice = (price) => {
	// 处理空值、null、undefined等情况
	if (price == null || price === '') {
		return '0.00';
	}

	// 转换为数字
	const priceNum = Number(price);

	// 验证是否为有效数字
	if (isNaN(priceNum) || !isFinite(priceNum)) {
		return '0.00';
	}

	// 分转元并格式化为两位小数
	return (priceNum / 100).toFixed(2);
};

/**
 * 注册事件
 */
initListener = () => {
	$(`.location`).on('click', e => {
		navigateTo(`page/address/city.html`)
	})
}
